package com.xusheng.cli.controller.back;

import cn.hutool.core.lang.RegexPool;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xusheng.cli.common.base.Attachment;
import com.xusheng.cli.common.base.MyPage;
import com.xusheng.cli.common.base.Result;
import com.xusheng.cli.common.enums.FileDirectoryEnum;
import com.xusheng.cli.common.exception.ServiceException;
import com.xusheng.cli.common.validation.Save;
import com.xusheng.cli.common.validation.Update;
import com.xusheng.cli.entity.clarityModule.Clarity;
import com.xusheng.cli.entity.videoModule.Video;
import com.xusheng.cli.service.ClarityService;
import com.xusheng.cli.service.VideoService;
import com.xusheng.cli.tools.FileUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.validation.constraints.Size;
import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * 清晰度(Clarity)表控制层
 *
 * @author whr
 * @since 2023-12-27 10:56:33
 */
@Slf4j
@Validated
@RestController
@RequestMapping("/api/v1/clarity")
public class ClarityController {
    /**
     * 服务对象
     */
    @Resource
    private ClarityService clarityService;
    @Resource
    private VideoService videoService;

    @Value("${serverIp}")
    private String serverIp;

    /**
     * 查询所有数据
     *
     * @param clarity 查询实体
     * @return 所有数据
     * @author whr
     * @since 2023-12-27 10:56:33
     */
    @GetMapping("queryAll")
    public Result<List<Clarity>> queryAll(Clarity clarity) {
        List<Clarity> list = clarityService.list(new QueryWrapper<>(clarity));
//        String serverIP = IpUtil.getInternetIp();
//        for (Clarity item : list) {
//            if (item.getIp() != null) {
//                if (item.getIp().equals(serverIP)) {
//                    item.setCurrent(true);
//                } else {
//                    item.setCurrent(false);
//                }
//            }
//        }
        return Result.success(list);
    }

    /**
     * 分页查询所有数据
     *
     * @param page    分页对象
     * @param clarity 查询实体
     * @return 所有数据
     * @author whr
     * @since 2023-12-27 10:56:33
     */
    @GetMapping("queryByPage")
    public Result<MyPage<Clarity>> queryByPage(MyPage<Clarity> page, Clarity clarity) {
        MyPage<Clarity> page1 = clarityService.page(page, new QueryWrapper<>(clarity));
//        String serverIP = IpUtil.getInternetIp();
//        for (Clarity item : page1.getRecords()) {
//            if (item.getIp() != null) {
//                if (item.getIp().equals(serverIP)) {
//                    item.setCurrent(true);
//                } else {
//                    item.setCurrent(false);
//                }
//            }
//        }
        return Result.success(page1);
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     * @author whr
     * @since 2023-12-27 10:56:33
     */
    @GetMapping("queryOne/{id}")
    public Result<Clarity> selectOne(@PathVariable Serializable id) {
        return Result.success(clarityService.getById(id));
    }

    /**
     * 新增数据
     *
     * @param clarity 实体对象
     * @return 新增结果
     * @author whr
     * @since 2023-12-27 10:56:33
     */
    @PostMapping("insert")
    public Result<Object> insert(@Validated(Save.class) Clarity clarity, @RequestParam(name = "file", required = false) MultipartFile file) {
        checkVideo(clarity, file);
//        String serverIP = IpUtil.getInternetIp();
//        clarity.setIp(serverIP);
//        log.info("Server IP address: " + serverIP);
        return Result.isSuccess(clarityService.save(clarity));
    }

    /**
     * 修改数据
     *
     * @param clarity 实体对象
     * @return 修改结果
     * @author whr
     * @since 2023-12-27 10:56:33
     */
    @PutMapping("update")
    public Result<Object> update(@Validated(Update.class) Clarity clarity, @RequestParam(name = "file", required = false) MultipartFile file) {
        if (file != null && !file.isEmpty()) {
            checkVideo(clarity, file);
        }
        return Result.isSuccess(clarityService.updateById(clarity));
    }

    /**
     * 删除单条数据
     *
     * @param id 主键
     * @return 删除结果
     * @author whr
     * @since 2023-12-27 10:56:33
     */
    @DeleteMapping("delete/{id}")
    public Result<Object> delete(@PathVariable Long id) {
        Clarity clarity = new Clarity();
        clarity.setId(id);
        return Result.isSuccess(clarityService.removeById(clarity));
    }

    /**
     * 批量删除数据
     *
     * @param idList 主键结合
     * @return 删除结果
     * @author whr
     * @since 2023-12-27 10:56:33
     */
    @DeleteMapping("batchDelete")
    public Result<Object> batchDelete(@Validated @Size(min = 1, message = "缺少删除所需的id") @RequestParam("idList") List<Long> idList) {
        return Result.isSuccess(clarityService.batchDelete(idList, new Clarity()));
    }

    private void checkVideo(Clarity clarity, MultipartFile file) {
        if (clarity.getSource() == 0) {
            if (file == null) {
                throw new ServiceException("请上传文件");
            }
            Video video = videoService.getById(clarity.getVideoId());
            Long categoryId = video.getCategoryId();
            Attachment attachment = FileUtils.uploadSingleFile(file, FileDirectoryEnum.ATTACHMENT.getDirectory() + File.separator + categoryId + File.separator + clarity.getVideoId());
            clarity.setUrl(serverIp + attachment.getUrl());
            clarity.setFileName(attachment.getPath());
        } else {
            if (StrUtil.isBlank(clarity.getUrl())) {
                throw new ServiceException("请输入视频链接地址");
            }
            if (!clarity.getUrl().matches(RegexPool.URL)) {
                throw new ServiceException("视频地址格式错误");
            }
        }
    }

    /**
     * 批量上传
     *
     * @param clarity
     * @param file
     * @return
     */
    @PostMapping("/batchUpload")
    public Result<Object> batchUpload(@Validated Clarity clarity, @RequestParam(name = "file", required = false) List<MultipartFile> file) {
        log.info("文件：{}", file);
        clarity.setSource(0);
        List<Clarity> videoList = new ArrayList<>();
        for (MultipartFile f : file) {
            checkVideo(clarity, f);
            Clarity clarity1 = new Clarity();
            clarity1.setUrl(clarity.getUrl());
            clarity1.setSource(clarity.getSource());
            clarity1.setVideoId(clarity.getVideoId());
            clarity1.setFileName(clarity.getFileName());
            clarity1.setIp(clarity.getIp());
            videoList.add(clarity1);
        }
        log.info("videoList：{}", videoList);
        return Result.isSuccess(clarityService.saveBatch(videoList));
    }
}

